# -*- coding: utf-8 -*-
import logging
import time
from integration.config.constants import *


class Logger(object):
    """
    封装日志模块
    """

    def __init__(self, logger, cmd_level=logging.INFO, file_level=logging.INFO):
        """

        :param logger:
        :param cmd_level:
        :param file_level:
        """
        try:
            self.logger = logging.getLogger(logger)
            self.logger.setLevel(logging.DEBUG)

            # 移除旧的 Handler，避免重复
            while self.logger.handlers:
                self.logger.removeHandler(self.logger.handlers[0])

            # 日志格式
            fmt = logging.Formatter(
                '%(asctime)s - %(filename)s:[%(lineno)s] - [%(levelname)s] - %(message)s'
            )

            # 控制台输出
            sh = logging.StreamHandler()
            sh.setFormatter(fmt)
            sh.setLevel(cmd_level)
            self.logger.addHandler(sh)

            # 文件输出
            curr_time = time.strftime("%Y-%m-%d")
            self.log_file_name = logPath + curr_time + '.txt'
            fh = logging.FileHandler(self.log_file_name)
            fh.setFormatter(fmt)
            fh.setLevel(file_level)
            self.logger.addHandler(fh)
        except Exception as e:
            raise e


if __name__ == '__main__':
    logger = Logger("fox", cmd_level=logging.DEBUG, file_level=logging.DEBUG)
    logger.logger.debug("debug")
    logger.logger.log(logging.ERROR, '%(module)s %(info)s', {'module': 'log日志', 'info': 'error'})  # ERROR,log日志 error
